package com.alpha.runes.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.alpha.runes.util.DisplayUtil;
import com.alpha.runes.util.LogUtils;
import com.alpha.runes.R;

/**
 * Date:2022-10-18
 * Time:11:33
 * author:colin
 */
public class FloatIconView extends RelativeLayout {


    private OnFloatIconViewClickListener onFloatIconViewClickListener;//悬浮窗监听点击事件
    private OnFloatIconViewLongClickListener onFloatIconViewLongClickListener;//悬浮窗监听点击事件

    private final static int LEFT = 0;
    private final static int RIGHT = 1;

    private int defPosition = RIGHT; //可变参数，随着吸附左右改变
    private WindowManager.LayoutParams wmParams;
    private WindowManager wm;
    private int screenHeight;
    private int screenWidth;
    private float mTouchStartX, mTouchStartY;
    private float x, y;
    private boolean isScroll;
    private int dpi;
    private Activity activity;
    private View view;


    private Handler mHandler = new Handler();

    public FloatIconView(Activity activity) {
        super(activity);
        this.activity = activity;
        init(activity);

    }

    public void init(Activity activity) {

        view = LayoutInflater.from(activity).inflate(R.layout.activity_float_item, this);

        DisplayMetrics dm = activity.getResources().getDisplayMetrics();
        int widthPixels = dm.widthPixels;
        int heightPixels = dm.heightPixels;

        wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);

        //屏宽
        screenWidth = wm.getDefaultDisplay().getWidth();
        //屏高
        screenHeight = wm.getDefaultDisplay().getHeight();
        //通过像素密度来设置按钮的大小
        dpi = dpi(dm.densityDpi);

        wmParams = new WindowManager.LayoutParams();
        wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION;
        wmParams.format = PixelFormat.RGBA_8888;//设置背景图片
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;//
        wmParams.gravity = Gravity.LEFT | Gravity.TOP;//
        wmParams.x = widthPixels; //设置位置像素
        wmParams.y =  heightPixels;
        wmParams.y = DisplayUtil.dip2px(activity, 60);
        wmParams.width = DisplayUtil.dip2px(activity, 60); //设置图片大小
        wmParams.height = DisplayUtil.dip2px(activity, 80);


//        wmParams.width = widthPixels; //设置图片大小
//        wmParams.height = heightPixels;
        wm.addView(view, wmParams);


    }

    /**
     * 设置点击事件监听
     *
     * @param onFloatIconViewClickListener
     */
    public void setOnFloatIconViewClickListener(OnFloatIconViewClickListener onFloatIconViewClickListener) {
        this.onFloatIconViewClickListener = onFloatIconViewClickListener;
    }

    public void setStart() {
//        ImageView iamgeView = view.findViewById(R.id.qiuspeed_img);
//        TextView textView = view.findViewById(R.id.qiuspeed_text);
//
//        iamgeView.setImageResource(R.drawable.qiuspeed_start);
//        textView.setText("未加速");
    }


    public void setPause() {
//        ImageView iamgeView = view.findViewById(R.id.qiuspeed_img);
//        TextView textView = view.findViewById(R.id.qiuspeed_text);
//
//        iamgeView.setImageResource(R.drawable.qiuspeed_run);
//
//        textView.setText("加速中");
    }

    public interface OnFloatIconViewClickListener {

        void onItemClick();


    }


    public interface OnFloatIconViewLongClickListener {
        void onItemLongClick();
    }

    /**
     * 设置点击事件监听
     *
     * @param onFloatIconViewLongClickListener
     */
    public void setOnFloatIconViewLongClickListener(OnFloatIconViewLongClickListener onFloatIconViewLongClickListener) {
        this.onFloatIconViewLongClickListener = onFloatIconViewLongClickListener;
    }


    private int startX;
    private int startY;
    private long startTime;
    private long pressreange = 2500;
    private long clickrange = 20;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 获取相对屏幕的坐标， 以屏幕左上角为原点
        x = event.getRawX();
        y = event.getRawY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = (int) event.getX();
                startY = (int) event.getY();
                startTime = System.currentTimeMillis();

                //无论悬浮窗是否处于隐藏状态，点击以后让悬浮窗显示出来即可
                view.setScrollX(0);

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (onFloatIconViewLongClickListener != null) {
                            onFloatIconViewLongClickListener.onItemLongClick();
                        }
                    }
                }, pressreange);

                break;
            case MotionEvent.ACTION_MOVE:

                float moveX = event.getX();
                float moveY = event.getY();

                LogUtils.debug("=333====ACTION_MOVE========================= move X---" + moveX + "-------------move Y--" + moveY);

                if (isScroll) {
                    updateViewPosition();
                } else {
                    // 当前不处于连续滑动状态 则滑动小于图标1/3则不滑动
                    if (Math.abs(mTouchStartX - event.getX()) > dpi / 3 || Math.abs(mTouchStartY - event.getY()) > dpi / 3) {
                        updateViewPosition();
                    } else {
                        break;
                    }
                }
                isScroll = true;
                int lastX = (int) event.getX();
                int lastY = (int) event.getY();

                if (Math.abs(lastX - startX) > clickrange || Math.abs(lastY - startY) > clickrange) {
                    this.mHandler.removeCallbacksAndMessages(null);
                }
                break;


            case MotionEvent.ACTION_UP:

                this.mHandler.removeCallbacksAndMessages(null);

                float moveXActionUp = event.getX();
                float moveYActionUp = event.getY();

                LogUtils.debug("=333====moveY  ActionUp========================= move X---" + moveXActionUp + "-------------move Y--" + moveYActionUp);
                // 拖动
                if (isScroll) {
                    //自动贴边代码增加在此处
                    autoView();
                } else {
                    //点击悬浮窗
                    if (System.currentTimeMillis() - startTime < pressreange) {
                        clickView();
                    }
                }
                isScroll = false;
                mTouchStartX = mTouchStartY = 0;
                break;
        }
        return true;
    }


    /**
     * 自动移动位置
     */
    private void autoView() {
        // 得到view在屏幕中的位置
        int[] location = new int[2];
        getLocationOnScreen(location);
        //左侧
        if (location[0] < screenWidth / 2 - getWidth() / 2) {
            updateViewPosition(LEFT);
        } else {
            updateViewPosition(RIGHT);
        }
    }

    /**
     * 更新浮动窗口位置参数
     */
    private void updateViewPosition() {
        wmParams.x = (int) (x);
        // 不设置为全屏(状态栏存在) 标题栏是屏幕的1/25
        wmParams.y = (int) (y - mTouchStartY - screenHeight / 25);
        wm.updateViewLayout(this, wmParams);
    }

    /**
     * 手指释放更新悬浮窗位置
     */
    private void updateViewPosition(int l) {
        switch (l) {
            case LEFT:
                defPosition = LEFT;
                //吸附后开启倒计时,倒计时结束后缩小图标
                wmParams.x = 0;
                break;
            case RIGHT:
                defPosition = RIGHT;
                int x = screenWidth - dpi;
                wmParams.x = x;
                break;
        }
        wm.updateViewLayout(this, wmParams);
    }

    /**
     * 根据密度选择控件大小
     */
    private int dpi(int densityDpi) {

        if (densityDpi <= 120) {

            return 36;

        } else if (densityDpi <= 160) {

            return 48;

        } else if (densityDpi <= 240) {

            return 72;

        } else if (densityDpi <= 320) {

            return 96;

        }

        return 108;

    }

    public void show() {
        if (isShown()) {
            return;
        }
        setVisibility(View.VISIBLE);
    }

    public void hide() {
        setVisibility(View.GONE);
    }

    public void destory() {
        hide();
        wm.removeViewImmediate(this);
    }

    //当悬浮按钮被点击
    public void clickView() {
        onFloatIconViewClickListener.onItemClick();
    }

    // 按钮长按事件
    private void longClickView() {
        onFloatIconViewLongClickListener.onItemLongClick();
    }

}
